package ecdhSev

import (
	"../ecdh"
	"crypto"
	"crypto/elliptic"
	"crypto/rand"
	"github.com/gogf/gf/g/container/gmap"
	"github.com/gogf/gf/g/crypto/gmd5"
	"github.com/gogf/gf/g/os/glog"
	"github.com/gogf/gf/g/util/gconv"
)

var EccKeyMap= gmap.NewStrAnyMap()
var Eh=ecdh.NewEllipticECDH(elliptic.P224())

type EccKey struct {
	PubKey []byte
	PriKey crypto.PrivateKey
	ClientPubKey []byte
	SharedSecret []byte
}

/*
生成加密对像
@param name string 用于缓存当前校验对象到map中
*/
func CreateECCKey(name string) *EccKey{
	eccKey:=&EccKey{}
	privKey, pubKey,err := Eh.GenerateKey(rand.Reader)
	if err != nil {
		glog.Error(err)
	}
	eccKey.PubKey= Eh.Marshal(pubKey)
	eccKey.PriKey=privKey
	EccKeyMap.Set(name,eccKey)
	return eccKey
}
/*用接收到的公钥加上本地的私钥生成共享的秘钥*/
func (this *EccKey)ComputerECCKeyMD5(pub []byte) []byte{
	pubKey,ok := Eh.Unmarshal(pub)
	this.ClientPubKey=pub
	if !ok {
		//glog.Error("Unmarshal does not work")
		return nil
	}
	var err error
	this.SharedSecret,err= Eh.GenerateSharedSecret(this.PriKey, pubKey)
	if err!=nil{
		//glog.Error(err)
		return nil
	}
	glog.Debug("ComputerECCKeyMD5:SharedSecret=",this.SharedSecret)
	return gconv.Bytes(gmd5.Encrypt(this.SharedSecret))
}